﻿jQuery.extend(jQuery.validator.defaults, { ignore: "" });
jQuery.validator.addMethod("mobile", function (value, element) {
    return this.optional(element) || /^1[0-9]{10}$/.test(value) || /^\d{3,4}\-?\d{7,8}$/.test(value);
});
jQuery.validator.addMethod("tel", function (value, element) {
    return this.optional(element) || /^\d{3,4}\-?\d{8}|\d{8}$/.test(value);
});
jQuery.validator.addMethod("idcard", function (value, element) {
    return this.optional(element) || /^([0-9]{17}[0-9X]{1})|([0-9]{15})$/.test(value);
});
jQuery.validator.addMethod("regex", function (value, element, params) {
    console.log(params);
    return this.optional(element) || eval(params).test(value);
});

$.validator.messages = {
    required: "不能为空",
    remote: "请完善此字段",
    email: "Email地址格式不正确",
    url: "URL地址不正确",
    date: "日期格式不正确",
    dateISO: "ISO日期格式不正确",
    number: "请输入有效的数字.",
    digits: "请输入整数.",
    creditcard: "请输入有效的信用卡号",
    equalTo: "请再次输入相同的值.",
    maxlength: $.validator.format("不能超过{0}个字符"),
    minlength: $.validator.format("不能少于{0}个字符"),
    rangelength: $.validator.format("长度不能超出{0}-{1}个字符"),
    range: $.validator.format("值范围应为{0}-{1}"),
    max: $.validator.format("最大值不能超出{0}"),
    min: $.validator.format("最小值不能超出{0}."),

    mobile: '电话号码格式不正确',
    tel: '电话号码格式不正确',
    regex: '格式不正确',
    idcard:'身份证号格式不正确'
};


(function ($) {
    /*
    全部验证规则
    */
    var rules = [
        'required',		//必填 用法required #自定义提示文字不能带空格，可省略，下同
        'remote',		//远程验证。。。
        'minlength',	//最小字符长度 用法minlength 10 #...
        'maxlength',	//最大字符长度 用法maxlength 20 #...
        'rangelength',	//字符长度范围 用法rangelength 3 18 #...
        'min',			//最小数值 用法min 1 #...
        'max',			//最大数值 用法max 100 #...
        'range',		//数值范围 用法range 10 100 #...
        'email',		//电子邮箱 用法email #...
        'url',			//Url地址格式 用法 url #...
        'date',			//日期格式 用法date #...
        'dateISO',		//ISO日期格式 用法 dateISO #...
        'number',		//数值格式 用法number #...
        'digits',		//非负整数数 用法digits #...
        'creditcard',	//信用卡号格式 用法creditcard #...
        'accept',
        'equalTo',		//与另外一个元素相等，填写元素的name 用法equalTo password #....
        //自定义
        'mobile',		//手机号码格式 用法mobile #.....
        'tel',			//电话号码格式 用法tel #...
        'regex',		//正则验证 用法 regex /\d/ #提示内容
        'idcard'
    ].sort(function (x, y) {
        return y.length - x.length;
    });


    var ruleFilterRex = eval('/( *' + rules.join('|') + ')([ ]+(?!' + rules.join('|') + ')[^# ][^ ]*)?([ ]+(?!' + rules.join('|') + ')[^# ][^ ]*)?([ ]+#[^ ]+)?/g');
    var ruleFilterRex1 = eval('/( *' + rules.join('|') + ')( +[^#][^ ]*)?( +[^#][^ ]*)?( +#[^ ]+)?/');
    var fieldDisplayNameRex = /\@[^ ]+/;
    $('form').livequery(function (index, form) {
        var validationOptions = {
            rules: {
            },
            messages: {
            }
        }
        $('input[data-vdt],select[data-vdt],textarea[data-vdt]', form).livequery(function (index, elm) {
            var $elm = $(elm);
            var rule = $elm.attr('data-vdt');
            if (!rule) return;
            var fieldName = $elm.attr('name') || $elm.attr('id'),
                fieldDisplayName,
                ruleName;
            if (!fieldName) {
                console.warn('元素的name或者id不能都为空！')
                return;
            }
            if (!$elm.attr('name')) {
                $elm.attr('name', fieldName);
            }
            var matcharray = rule.match(ruleFilterRex);

            if (!matcharray) {
                console.warn('验证规则不正确！' + rule);
                return;
            }
            validationOptions.rules[fieldName] = {};
            validationOptions.messages[fieldName] = {};

            var displaymatch = fieldDisplayNameRex.exec(rule);
            fieldDisplayName = displaymatch ? displaymatch[0].substring(1) : null;


            for (var x = 0; x < matcharray.length;x++) {

                var match = ruleFilterRex1.exec(matcharray[x]);
                for (var i = 0; i < match.length; i++) {
                    ruleName =$.trim( match[1]);
                    var p1 = match[2];
                    var p2 = match[3];
                    var msg = match[4];

                    if (!p1) {
                        validationOptions.rules[fieldName][ruleName] = true;
                    }
                    else {
                        p1 = $.trim(p1);
                        p1 = $.isNumeric(p1) ? parseFloat(p1) : p1;
                        if (!p2) {
                            validationOptions.rules[fieldName][ruleName] = p1;
                        }
                        else {

                            p2 = $.trim(p2);
                            p2 = $.isNumeric(p2) ? parseFloat(p2) : p2;
                            validationOptions.rules[fieldName][ruleName] = [p1, p2];
                        }
                    }
                    if (msg) {
                        validationOptions.messages[fieldName][ruleName] = /*(fieldDisplayName ? fieldDisplayName + ' ' : '') + */$.trim(msg).substring(1);
                    }

                }
            }

            $elm.removeAttr('data-vdt')
            $(form).removeData('validator').validate(validationOptions);
        });
    });


})(jQuery);
